﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ChatTool
{
    public class RemoteHelpClient
    {
        private bool isExit = false;//判断连接是不是正常断开
        private UserClient userClient;//客户端连接对象
        private FormChatToOne formChatToOne;//QQtoOne窗体的引用
        //private MouseAndKey mak = new MouseAndKey();//鼠标键盘模拟对象

        private int imageWidth;
        private int imageHeight;
        public RemoteHelpClient(FormChatToOne formChatToOne)
        {
            this.formChatToOne = formChatToOne;
            imageHeight = 600;
            imageWidth = Screen.AllScreens[0].Bounds.Width * 600 / Screen.AllScreens[0].Bounds.Height;
        }
        public void StartConnectServer()
        {
            Thread threadConnect = new Thread(ConnectServer);
            threadConnect.IsBackground = true;
            threadConnect.Start();
        }
        private void ConnectServer()
        {
            TcpClient client = new TcpClient(AddressFamily.InterNetwork);
            try
            {
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.formChatToOne.UserClient.User.Ip), this.formChatToOne.UserClient.User.ListenerPort);
                client.Connect(ipe);//连接服务器
            }
            catch
            {
                client.Close();
                MessageBox.Show("连接服务器失败,可能对方服务器未开启.");
                return;
            }
            formChatToOne.SetButtonText("tsbRemoteControl", "停止协助");

            userClient = new UserClient(client);
            Thread receiveThread = new Thread(ReceiveServerData);
            receiveThread.IsBackground = true;
            receiveThread.Start();

            NetManager.SendStringMsgToServer(userClient, "RemoteHelp");//远程协助请求命令
        }
        /// <summary>
        /// 接受服务端信息的线程方法体
        /// </summary>
        private void ReceiveServerData()
        {
            while (isExit == false)
            {
                try
                {
                    string command = userClient.Br.ReadString().ToLower();
                    switch (command.ToLower())
                    {
                        case "refuse":
                            formChatToOne.SetButtonText("tsbRemoteControl", "远程协助");
                            userClient.Close();
                            MessageBox.Show("对方拒绝了你的远程协助请求!");
                            return;
                        case "agree":
                            BeginSendDesktopImageToServer();//这里应该用一个新的线程进行发送 不然就会在传送图片时无法收到服务端的协助命令了
                            break;
                        //case "helpcommand":
                        //    ParseHelpCommand(userClient);
                        //    break;
                        case "stopremotehelp":
                            formChatToOne.SetButtonText("tsbRemoteControl", "远程协助");
                            userClient.Close();
                            return;
                        case "fullscreen":
                            this.imageWidth = Screen.AllScreens[0].Bounds.Width;
                            this.imageHeight = Screen.AllScreens[0].Bounds.Height;
                            break;
                        case "partscreen":
                            this.imageWidth = Screen.AllScreens[0].Bounds.Width * 600 / Screen.AllScreens[0].Bounds.Height;
                            this.imageHeight = 600;
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                    if (isExit == false)
                    {
                        formChatToOne.SetButtonText("tsbRemoteControl", "远程协助");
                        userClient.Close();
                        MessageBox.Show("对方停止了对你的远程协助!");
                        return;
                    }
                    return;
                }
            }
        }
        ///// <summary>
        ///// 解析对方的远程协助命令
        ///// </summary>
        //private void ParseHelpCommand(UserClient userClient)
        //{
        //    string whichOne = "";
        //    string command = userClient.Br.ReadString().ToLower();
        //    try
        //    {
        //        switch (command)
        //        {
        //            case "mousemove"://鼠标移动
        //                string[] localString = userClient.Br.ReadString().Split('@');
        //                int localX = int.Parse(localString[0]);
        //                int localY = int.Parse(localString[1]);
        //                int remoteFormHeight = int.Parse(localString[2]);
        //                double rate = ((double)Screen.AllScreens[0].Bounds.Height) / remoteFormHeight;
        //                mak.SetCursorPosition((int)(localX * rate), (int)(localY * rate));
        //                break;
        //            case "mousedown"://鼠标键的按下
        //                whichOne = userClient.Br.ReadString().ToLower();
        //                if (whichOne == "left")
        //                    mak.MouseDown(MouseAndKey.ClickOnWhat.LeftMouse);
        //                else if (whichOne == "middle")
        //                    mak.MouseDown(MouseAndKey.ClickOnWhat.MiddleMouse);
        //                else if (whichOne == "right")
        //                    mak.MouseDown(MouseAndKey.ClickOnWhat.RightMouse);
        //                break;
        //            case "mouseup"://鼠标键的抬起
        //                whichOne = userClient.Br.ReadString().ToLower();
        //                if (whichOne == "left")
        //                    mak.MouseUp(MouseAndKey.ClickOnWhat.LeftMouse);
        //                else if (whichOne == "middle")
        //                    mak.MouseUp(MouseAndKey.ClickOnWhat.MiddleMouse);
        //                else if (whichOne == "right")
        //                    mak.MouseUp(MouseAndKey.ClickOnWhat.RightMouse);
        //                break;
        //            case "keypress"://键盘键的按下即抬起
        //                int keyValue = int.Parse(userClient.Br.ReadString());
        //                MouseAndKey.VirtualKeys virtualKey = (MouseAndKey.VirtualKeys)(Enum.ToObject(typeof(MouseAndKey.VirtualKeys), keyValue));
        //                mak.KeyPress(virtualKey); 
        //                break;
        //            case "mousewheel"://鼠标滚轮的滚动
        //                int delta = int.Parse(userClient.Br.ReadString());
        //                mak.MouseWheel(delta);
        //                break;
        //            default:
        //                break;
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //}

        private void BeginSendDesktopImageToServer()
        {
            Thread sendThread = new Thread(SendDesktopImage);
            sendThread.IsBackground = true;
            sendThread.Start();
        }
        /// <summary>
        /// 发送自己的桌面图片
        /// </summary>
        private void SendDesktopImage()
        {
            while (isExit == false)
            {
                //获取桌面的数据
                Bitmap desktopImage = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height);
                using (Graphics g = Graphics.FromImage(desktopImage))
                {
                    g.CopyFromScreen(new Point(0,0), new Point(0, 0), desktopImage.Size);
                }
                //在这里对图片进行相对的缩放 以适应远程控制方的要求
                desktopImage = new Bitmap(desktopImage, imageWidth, imageHeight);
                using (MemoryStream ms = new MemoryStream())
                {
                    if (desktopImage != null)
                    {
                        desktopImage.Save(ms, ImageFormat.Jpeg);
                        byte[] bs = ms.GetBuffer();
                        try
                        {
                            NetManager.SendBytesMsgToServer(userClient, bs);
                            Thread.Sleep(300);
                        }
                        catch
                        {
                            if (isExit == false)
                            {
                                formChatToOne.SetButtonText("toolStripButtonRemoteHelp", "远程协助");
                                isExit = true;
                                userClient.Close();
                                MessageBox.Show("对方停止了对你的远程协助.");
                                return;
                            }
                            formChatToOne.SetButtonText("toolStripButtonRemoteHelp", "远程协助");
                            isExit = true;
                            userClient.Close();
                            break;
                        }
                        finally
                        {
                            desktopImage.Dispose();
                            desktopImage = null;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 停止远程协助
        /// </summary>
        public void StopRemoteHelpClient()
        {
            this.isExit = true;
            NetManager.SendStringMsgToServer(userClient, "StopRemoteHelp");
            formChatToOne.SetButtonText("tsbRemoteControl", "远程协助");
            userClient.Close();
        }
    }
}
